/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package braipetro.client.base;

import braipetro.data_access.DataSet;
import java.awt.event.KeyEvent;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author manasses
 */
public class FrmBaseList extends FrmBase {
    protected FrmBaseDet det;
    private List<GridColumn> grdCol = new LinkedList<GridColumn>();
    protected JTable grd;
    
    /**
     * Creates new form FrmBaseList
     * @param parent
     * @param modal
     */
    public FrmBaseList(FrmBase parent, boolean modal, String pDet, DataSet dataSet)  {
        super(parent, modal, dataSet);
        initComponents();
       
        instanceDet(pDet);
    }
    
    protected void setGrid(JTable tb) {
        grd = tb;
        
        grd.setCellSelectionEnabled(false);
        grd.setRowSelectionAllowed(true);
        ListSelectionModel cellSelectionModel = grd.getSelectionModel();
        //cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        
        cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                dts.gotoPos(grd.getSelectedRow() + 1);
            }
        });
    }
    
    public void addGridColumn(String field, String label, int width) {
        GridColumn tbcol = new GridColumn(field, label, width);
        grdCol.add(tbcol);    
    }
    
    protected void createGridColumns() {
        DefaultTableModel dm = (DefaultTableModel)grd.getModel();
        
        for (int i = 0; i < grdCol.size(); i++) {   
            dm.addColumn(grdCol.get(i).getLabel());     
        }
        
        for (int i = 0; i < grdCol.size(); i++) {
            grd.getColumnModel().getColumn(i).setPreferredWidth(grdCol.get(i).getWidth());
        }
    }
    
    private void instanceDet(String pDet) {
        
        try {
            Class c = Class.forName(pDet);
            Constructor ct = c.getConstructor(FrmBase.class, boolean.class, DataSet.class);
            Object obj = ct.newInstance(this, true, dts);
            det = (FrmBaseDet)obj;
            
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(FrmBaseList.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchMethodException ex) {
            Logger.getLogger(FrmBaseList.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(FrmBaseList.class.getName()).log(Level.SEVERE, null, ex);    
        } catch (InstantiationException ex) {
            Logger.getLogger(FrmBaseList.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(FrmBaseList.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(FrmBaseList.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvocationTargetException ex) {
            Logger.getLogger(FrmBaseList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    protected void clearCompDet() {
        for (int i = 0; i < det.getBindings().size(); i++) {
            ((JTextField)det.getBindings().get(i).getCmp()).setText("");
         }
    }

    protected void addItem() {
        det.setLocationRelativeTo(this);
        clearCompDet();
        det.setVisible(true);
        int result = det.getModalResult();
        
        if (result == 1){
            dts.append();
            
            for (int i = 0; i < det.getBindings().size(); i++) {
                dts.setValue(det.getBindings().get(i).getField(), ((JTextField)det.getBindings().get(i).getCmp()).getText());
            }
 
            dts.post();
            
            clearGrid();
            populateGrid();
            
        } else {}
    }
    
    protected void editItem() {
        det.setLocationRelativeTo(this);
        
         for (int i = 0; i < det.getBindings().size(); i++) {
             JComponent cmp = det.getBindings().get(i).getCmp();
             if (cmp instanceof JTextField) {
                ((JTextField)cmp).setText(dts.getValue(det.getBindings().get(i).getField()));
             } else if (cmp instanceof JComboBox) {
                 
             }
         }
        
        det.setVisible(true);
        int result = det.getModalResult();
        
        if (result == 1){
             
           dts.edit();
            
            for (int i = 0; i < det.getBindings().size(); i++) {
                dts.setValue(det.getBindings().get(i).getField(), ((JTextField)det.getBindings().get(i).getCmp()).getText());
            }
 
            dts.post();
            
            clearGrid();
            populateGrid();
            
        } else {}
    }
    
    protected void delItem() {
        dts.delete();
        
        clearGrid();
        populateGrid();
    }
    
    public void populateGrid() {
        dts.savePos();
         
        dts.beforeFirst();
        
        while (dts.next()) {
            Vector vec = new Vector();
            
            for (int i = 0; i < grdCol.size(); i++) {
                vec.add(dts.getValue(grdCol.get(i).getField()));
            }
            
            ((DefaultTableModel)grd.getModel()).addRow(vec);
           
        }
        
        dts.gotoSavedPos();
    }
    
    private void clearGrid() {
        DefaultTableModel dm = (DefaultTableModel)grd.getModel();
        int count = dm.getRowCount();
        
        while (count > 0) {
            dm.removeRow(0);
            count = dm.getRowCount();
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_F5){
            addItem();
        }
        else if (evt.getKeyCode() == KeyEvent.VK_F6) {
            editItem();
        }
        else if (evt.getKeyCode() == KeyEvent.VK_F8){
            delItem();
        }
    }//GEN-LAST:event_formKeyPressed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        
    }//GEN-LAST:event_formWindowActivated

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        dts.open();
        populateGrid();
    }//GEN-LAST:event_formWindowOpened

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        dts.close();
    }//GEN-LAST:event_formWindowClosing

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
